<?php
/*
 * 
 * post category module
 */
 class category{
 	
	protected $_db;
	function __construct(){
		$this->_db = db::getInstance();
		$this->v = new view();
		$this->v->init(TRUE);
	}
	
	public function index()
	{
		if(isset($_REQUEST['id']))
		{
			$cid = intval($_REQUEST['id']);
			$cat = $this->get_category_info($cid);
		}else{
			$cat = array();
		}
		$cat_list = get_category_list();
		$cat_list = cat_options(0, $cat_list);
		$data = array();
		$data['cat'] = $cat;
		$data['cat_list'] = $cat_list;
		$page = isset($_REQUEST['page'])?$_REQUEST['page']:'0';
		$data['page'] = $page;
		$this->v->load('header');		
		$this->v->load('cat_list', $data);	
		$this->v->load('footer');
	}
	
	public function edit()
	{
		if(empty($_POST)){
			redirect('spider/spider.php?mod=category');
			return FALSE;
		}
		$post = $_POST;	
		$data = array();
		if(empty($post['cat_name'])){
			redirect('spider/spider.php?mod=category');	
			return FALSE;
		}
		$data['cat_name'] = $post['cat_name'];
		if(empty($post['cat_en_name'])){
			redirect('spider/spider.php?mod=category');	
			return FALSE;
		}
		$data['cat_en_name'] = $post['cat_en_name'];
		$data['pid'] = $post['pid'];
		$data['dis'] = $post['dis'];
		if(!empty($post['cid'])){
			$sql = "update category set cat_name='".$data['cat_name']."', cat_en_name='".$data['cat_en_name']."', pid='".$data['pid'];
			$sql .= "', dis='".$data['dis']."' where cid='".$post['cid']."'";
			if($this->_db->query($sql) == FALSE){
				echo 'category update error';
				echo $sql;
				return false;
			}
		}else{
			if($this->_db->insert('category', $data) == FALSE){
				echo 'post save error';
				return FALSE;
			}
		}
		
		redirect('spider/spider.php?mod=category');
		return FALSE;
	}
	
	public function del()
	{
		if(!isset($_GET['id'])){
			redirect('spider/spider.php?mod=category');	
			return FALSE;
		}
		$id = intval($_GET['id']);
		$post = $this->_db->query("select id from posts where category='".$id."'")->result_array();
		
		if(!empty($post)){
			redirect('spider/spider.php?mod=category');		
			return FALSE;
		}
		$cat = $this->_db->query("select cid from category where pid='".$id."'")->result_array();
		if(!empty($cat)){
			redirect('spider/spider.php?mod=category');	
			return FALSE;
		}
		$this->_db->query('delete from category where cid='.$id);
		redirect('spider/spider.php?mod=category');		
	}
	
	/*******************************model ********************************/
	function get_category_info($cid)
	{
		$sql = 'select * from category where cid='.$cid;
		$db = db::getInstance();
		$cat = $db->query($sql)->result_array();
		if(empty($cat)){
			return FALSE;
		}
		return $cat[0];
	}
	
	function get_category_list()
	{
		$sql = 'select * from category';
		$db = db::getInstance();
		$cat = $this->_db->query($sql)->result_array();
		
		return $cat;
	}
	
 }
?>